//
//  DBNavigatorTool.swift
//  DBCA
//
//  Created by mugua on 2024/6/30.
//

import UIKit


class DBNavigator {
    
    static func rootViewController() -> UIViewController? {
        if let window = UIApplication.shared.delegate?.window {
            return window?.rootViewController
        }
        return nil
    }
    
    static func keyWindow() -> UIWindow? {
        if #available(iOS 13.0, *) {
            let winScene = UIApplication.shared.connectedScenes.first as? UIWindowScene
            return winScene?.windows.first
        } else {
            return UIApplication.shared.keyWindow
        }
    }
    
    static func currentViewControllerFrom(viewController: UIViewController?) -> UIViewController? {
        
        guard let viewController = viewController else { return nil }
        
        if viewController.isKind(of: DBBaseNavigationController.self) {
            let navigationController = viewController as! UINavigationController
            return currentViewControllerFrom(viewController: navigationController.viewControllers.last)
            
        } else if viewController.isKind(of: DBBaseTabBarController.self) {
            let tabBarController = viewController as! UITabBarController
            return currentViewControllerFrom(viewController: tabBarController.selectedViewController)
            
        } else if let presentedViewController = viewController.presentedViewController {
            return currentViewControllerFrom(viewController: presentedViewController)
        }
        
        return viewController
    }
    
    static func currentViewController() -> UIViewController? {
        return currentViewControllerFrom(viewController: rootViewController())
    }
    
    static func currentNavigationController() -> UINavigationController? {
        return currentViewController()?.navigationController
    }
    
}
